package cn.cangfei.massage.controller;

import cn.cangfei.massage.common.api.CommonPage;
import cn.cangfei.massage.common.api.CommonResult;
import cn.cangfei.massage.constant.RedisConstants;
import cn.cangfei.massage.dto.MassageDoctorDTO;
import cn.cangfei.massage.dto.MassageDoctorListDto;
import cn.cangfei.massage.dto.custom.MassageDoctorDTOFinal;
import cn.cangfei.massage.dto.param.MassageDoctorParam;
import cn.cangfei.massage.dto.update.MassageDoctorListDtoWithAdmin;
import cn.cangfei.massage.entity.MassageDoctor;
import cn.cangfei.massage.entity.PowerConfig;
import cn.cangfei.massage.service.IMassageDoctorService;
import cn.cangfei.massage.service.IMassageInfoService;
import cn.cangfei.massage.service.IPowerConfigService;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author Lemon  2313812755@qq.com
 * @date 2023/2/4
 */

@Api(value = "推拿馆模块", tags = "师傅信息接口")
@RestController
@CrossOrigin
@RequestMapping("/massage")
public class MassageDoctorController {

    private static final int GIRL = 2;
    private static final int BOY = 1;


    @Resource
    private IMassageInfoService infoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Resource
    private IMassageDoctorService doctorService;

    @Resource
    private IPowerConfigService powerConfigService;

    // TODO
    @ApiOperation(value = "根据推拿馆id来查询师傅(小程序端)", notes = "传入 科室id")
    @RequestMapping(value = "/getDoctorByMassageIdAndDay", method = RequestMethod.GET)
    public CommonResult<MassageDoctorListDto> getDoctorByMassageId(@RequestParam("massageId") Long massageId, @RequestParam("day") String day) throws ParseException {

        if (!infoService.count(massageId)) {
            return CommonResult.validateFailed("不存在，该推拿馆编号！");

        }
        // 根据这个day来判断是星期几
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        Date date = formatter.parse(day);
        String[] weekEnds = {"0", "1", "3", "3", "5", "5", "1", "1"};
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        // week表示星期
        String week = weekDays[w];
//        System.out.println("week:" + week);
        // 根据星期来查询

        // 获取配置
        // 从redis中获取
        String key = RedisConstants.POWER_CONFIG_PREFIX;
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        PowerConfig configInfo = null;
        if (StringUtils.isEmpty(jsonStr)) {
            configInfo = powerConfigService.getConfigInfo(1L);
            // 存入redis
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(configInfo));
        } else {
            configInfo = JSON.parseObject(jsonStr, PowerConfig.class);
        }
        String isShow = configInfo.getIsShow();
        String time = configInfo.getTime();
        // 如果没有配置时间，就默认20:00
        if (StringUtils.isEmpty(time)) {
            time = "20:00";
        }
        int weekEnd = 0;
        // 获取到当前时间只获取时分的格式
        SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm");
        Date date1 = new Date();
        // format就表示发号的时间点
        String format = formatter1.format(date1);
        // format必须大于等于time才能够发号
        // 注意这个week是当前时间
        Date date2 = new Date();
        // 年月日的格式
        String format1 = formatter.format(date2);
        Date date3 = formatter.parse(format1);
        Calendar cal1 = Calendar.getInstance();
        cal.setTime(date3);
        int w1 = cal1.get(Calendar.DAY_OF_WEEK) - 1;
        if (w1 < 0)
            w1 = 0;
        // week表示星期
        String weekFinal = weekDays[w1];

        if (("1".equals(weekFinal) || "3".equals(weekFinal) || "5".equals(weekFinal)) && (format.compareTo(time) >= 0)) {

            if ("1".equals(weekFinal)) {
                weekEnd = 3;
            }
            if ("3".equals(weekFinal)) {
                weekEnd = 5;
            }
            if ("5".equals(weekFinal)) {
                weekEnd = 1;
            }

        } else {
            weekEnd = Integer.parseInt(weekEnds[Integer.parseInt(week)]);
        }
        MassageDoctorListDto massageDoctorListDto = new MassageDoctorListDto();
        massageDoctorListDto.setIsShow(isShow);

        // 放置应该显示到星期几
        massageDoctorListDto.setWeek(weekEnd);

        //
        List<MassageDoctorDTOFinal> doctorlist = doctorService.getDoctorByMassageId(massageId, week, day);
        massageDoctorListDto.setDoctorlist(doctorlist);
        return CommonResult.success(massageDoctorListDto);
    }

    @ApiOperation(value = "根据推拿馆id来查询师傅(管理端)", notes = "传入 科室id")
    @RequestMapping(value = "/admin/getDoctorByMassageIdAndDay", method = RequestMethod.GET)
    public CommonResult<MassageDoctorListDtoWithAdmin> getDoctorByMassageIdForAdmin(@RequestParam("massageId") Long massageId, @RequestParam("day") String day) throws ParseException {

        if (!infoService.count(massageId)) {
            return CommonResult.validateFailed("不存在，该推拿馆编号！");

        }

        // 根据这个day来判断是星期几
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        Date date = formatter.parse(day);
        String[] weekEnds = {"0", "1", "3", "3", "5", "5", "7", "7"};
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        // week表示星期
        String week = weekDays[w];
//        System.out.println("week:" + week);
        // 根据星期来查询

        // 获取配置
        PowerConfig configInfo = powerConfigService.getConfigInfo(1L);
        String isShow = configInfo.getIsShow();
        String time = configInfo.getTime();
        // 如果没有配置时间，就默认20:00
        if (StringUtils.isEmpty(time)) {
            time = "20:00";
        }
        int weekEnd = 0;
        // 获取到当前时间只获取时分的格式
        SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm");
        Date date1 = new Date();
        // format就表示发号的时间点
        String format = formatter1.format(date1);
        // format必须大于等于time才能够发号
        // 注意这个week是当前时间
        Date date2 = new Date();
        // 年月日的格式
        String format1 = formatter.format(date2);
        Date date3 = formatter.parse(format1);
        Calendar cal1 = Calendar.getInstance();
        cal.setTime(date3);
        int w1 = cal1.get(Calendar.DAY_OF_WEEK) - 1;
        if (w1 < 0)
            w1 = 0;
        // week表示星期
        String weekFinal = weekDays[w1];

        if (("1".equals(weekFinal) || "3".equals(weekFinal) || "5".equals(weekFinal) || "7".equals(weekFinal)) && (format.compareTo(time) >= 0)) {

            if ("1".equals(weekFinal)) {
                weekEnd = 3;
            }
            if ("3".equals(weekFinal)) {
                weekEnd = 5;
            }
            if ("5".equals(weekFinal)) {
                weekEnd = 7;
            }
            if ("7".equals(weekFinal)) {
                weekEnd = 2;
            }
        } else {
            weekEnd = Integer.parseInt(weekEnds[Integer.parseInt(week)]);
        }
        MassageDoctorListDtoWithAdmin massageDoctorListDto = new MassageDoctorListDtoWithAdmin();
        massageDoctorListDto.setIsShow(isShow);

        // 放置应该显示到星期几
        massageDoctorListDto.setWeek(weekEnd);

        List<MassageDoctorDTO> doctorlist = doctorService.getDoctorByMassageIdForAdmin(massageId, week, day);
        massageDoctorListDto.setDoctorlist(doctorlist);
        return CommonResult.success(massageDoctorListDto);
    }

    @ApiOperation(value = "根据推拿馆id来查询师傅", notes = "传入 科室id")
    @RequestMapping(value = "/getDoctorByMassageId", method = RequestMethod.GET)
    public CommonResult<CommonPage<MassageDoctorDTO>> getDoctorByMassageId(@RequestParam("massageId") Long
                                                                                     massageId,
                                                                           @RequestParam(name = "name", required = false) String name,
                                                                           @RequestParam Integer pageNum, @RequestParam Integer pageSize) throws ParseException {
        if (!infoService.count(massageId)) {
            return CommonResult.validateFailed("不存在，该店铺编号！");

        }


        // 根据推拿馆id
        List<MassageDoctorDTO> doctorlist = doctorService.getDoctorByMassageId(massageId, name, pageNum, pageSize);

        return CommonResult.success(CommonPage.restPage(doctorlist));
    }


    @ApiOperation(value = "添加师傅信息", notes = "传入 师傅信息参数（姓名，性别，职称，专长，所属专科，所属门诊）")
    @RequestMapping(value = "/doctor", method = RequestMethod.POST)
    public CommonResult insertDoctor(@RequestBody MassageDoctorParam param) {

        if (param.getGender() > GIRL || param.getGender() < BOY) {
            return CommonResult.validateFailed("性别参数错误！");
        }


        if (doctorService.insert(param)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "查询全部师傅信息", notes = "传入 不需要参数")
    @RequestMapping(value = "/list/doctor", method = RequestMethod.GET)
    public CommonResult<List<MassageDoctor>> getAllDoctor() {

        List<MassageDoctor> list = doctorService.getAllDoctor();


        return CommonResult.success(list);
    }

    @ApiOperation(value = "更新师傅信息", notes = "传入 师傅编号、师傅信息参数（姓名，性别，职称，专长，所属专科，所属门诊）")
    @ApiImplicitParam(name = "id", value = "师傅编号", paramType = "path", dataType = "Long", required = true)
    @RequestMapping(value = "/doctor/{id}", method = RequestMethod.PUT)
    public CommonResult updateDoctor(@PathVariable Long id, @RequestBody MassageDoctorParam param) {

        if (!doctorService.count(id)) {
            return CommonResult.validateFailed("不存在，该师傅编号");
        }

        if (!doctorService.countMassageId(param.getMassageId())) {
            return CommonResult.validateFailed("不存在，该店铺编号");

        }

        if (param.getGender() > GIRL || param.getGender() < BOY) {
            return CommonResult.validateFailed("性别参数错误！");
        }

        if (doctorService.update(id, param)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "删除师傅信息", notes = "传入 师傅编号")
    @ApiImplicitParam(name = "id", value = "师傅编号", paramType = "path", dataType = "Long", required = true)
    @RequestMapping(value = "/doctor/{id}", method = RequestMethod.DELETE)
    public CommonResult deleteDoctor(@PathVariable Long id) {
        if (!doctorService.count(id)) {
            return CommonResult.validateFailed("不存在，该师傅编号");
        }

        if (doctorService.delete(id)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "分页：通过姓名,推拿馆名称，搜索师傅信息", notes = "传入 师傅姓名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "师傅姓名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer",
                    required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer",
                    required = true),
    })
    @RequestMapping(value = "/doctor/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<MassageDoctorDTO>> searchDoctor(@RequestParam(required = false) String name,
                                                                    @RequestParam Integer pageNum,
                                                                    @RequestParam Integer pageSize,
                                                                    @RequestParam(required = false) Long massageId) {

        return CommonResult.success(CommonPage.restPage(doctorService.list(name, pageNum, pageSize, massageId)));
    }

    @ApiOperation(value = "分页：通过专科、门诊，查找师傅信息", notes = "传入 专科编号、门诊编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "specialId", value = "专科编号", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "outpatientId", value = "门诊编号", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer",
                    required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer",
                    required = true),
    })
    @RequestMapping(value = "/doctor/list/special/outpatient", method = RequestMethod.GET)
    public CommonResult listDoctorBySpecialAndOutpatient(@RequestParam(required = false) Long specialId,
                                                         @RequestParam(required = false) Long outpatientId,
                                                         @RequestParam Integer pageNum,
                                                         @RequestParam Integer pageSize) {

        return CommonResult.success(CommonPage.restPage(doctorService.list(null, specialId, outpatientId, pageNum, pageSize)));

    }

    @ApiOperation(value = "分页：通过姓名、专科、门诊，搜索师傅信息", notes = "传入 师傅姓名、专科编号、门诊编号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "师傅姓名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "specialId", value = "专科编号", paramType = "query", dataType = "Long"
                    , required = true),
            @ApiImplicitParam(name = "outpatientId", value = "门诊编号", paramType = "query", dataType = "Long"
                    , required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer",
                    required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer",
                    required = true),
    })
    @RequestMapping(value = "/doctor/list/name", method = RequestMethod.GET)
    public CommonResult listDoctorBySpecialAndOutpatientAndName(@RequestParam(required = false) String name,
                                                                @RequestParam Long specialId,
                                                                @RequestParam Long outpatientId,
                                                                @RequestParam Integer pageNum,
                                                                @RequestParam Integer pageSize) {

        return CommonResult.success(CommonPage.restPage(doctorService.list(name, specialId, outpatientId, pageNum, pageSize)));

    }


    @ApiOperation(value = "获取师傅信息", notes = "传入 师傅编号")
    @ApiImplicitParam(name = "id", value = "师傅编号", paramType = "path", dataType = "Long", required = true)
    @RequestMapping(value = "/doctor/{id}", method = RequestMethod.GET)
    public CommonResult<MassageDoctorDTO> getDoctor(@PathVariable Long id) {
        if (!doctorService.count(id)) {
            return CommonResult.validateFailed("不存在，该师傅编号");
        }

        Optional<MassageDoctorDTO> doctorOptional = doctorService.getConvert(id);

        return doctorOptional.map(CommonResult::success)
                .orElseGet(() -> CommonResult.failed("服务器错误，请联系管理员！"));

    }

}
